import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ReactTooltip from 'react-tooltip';
import classnames from 'classnames';
import * as cookiesManager from '../cookiesManager';
import * as appPropTypes from './appPropTypes';
import { withRoomContext } from '../RoomContext';
import * as stateActions from '../redux/stateActions';
import PeerView from './PeerView';
import micophoneOpen from '../assets/img/7.png'
import micophoneClose from '../assets/img/3.png'
import cameraOpen from '../assets/img/8.png'
import cameraClose from '../assets/img/5.png'
import leaveMeeting from '../assets/img/4.png'
import { Modal } from 'antd';
import requestApi from '../../api/request';

class Me extends React.Component {
	constructor(props) {
		super(props);

		this._mounted = false;
		this._rootNode = null;
		this.peerViewRef = React.createRef();

		this.state = {
			meetingEnded: false,
			speakerHighVolume: false
		};
	}

	toggleVolume() {
		const newVolume = this.state.speakerHighVolume ? 10 : 2;
		if (this.peerViewRef.current) {
			this.peerViewRef.current.setAudioVolume(newVolume);
		}
	}

	render() {
		const {
			roomClient,
			me,
			audioProducer,
			onSetStatsPeerId,
		} = this.props;

		let micState;

		if (!me.canSendMic) micState = 'unsupported';
		else if (!audioProducer) micState = 'unsupported';
		else if (!audioProducer.paused) micState = 'on';
		else micState = 'off';

		let tip;

		if (!me.displayNameSet) tip = 'Click on your name to change it';

		return (
			<div
				data-component="Me"
				ref={node => (this._rootNode = node)}
				data-tip={tip}
				data-tip-disable={!tip}
			>
				{!this.state.meetingEnded && (
					<>
						<PeerView
							isMe
							peer={me}
							audioProducerId={audioProducer ? audioProducer.id : null}
							audioRtpParameters={
								audioProducer ? audioProducer.rtpParameters : null
							}
							audioTrack={audioProducer ? audioProducer.track : null}
							audioCodec={audioProducer ? audioProducer.codec : null}
							audioScore={audioProducer ? audioProducer.score : null}
							onChangeDisplayName={displayName => {
								roomClient.changeDisplayName(displayName);
							}}
							onChangeMaxSendingSpatialLayer={spatialLayer => {
								roomClient.setMaxSendingSpatialLayer(spatialLayer);
							}}
							onStatsClick={onSetStatsPeerId}
							ref={this.peerViewRef}
						/>

						{/* Control bar */}
						<div className="controls-bar">
							{/* Microphone button */}
							<div 
								className="control-button"
								onClick={() => {
									if (micState === 'on') {
										roomClient.disableMic();
									} else {
										roomClient.enableMic();
									}
								}}
							>
								<img 
									src={micState === 'on' ? micophoneOpen : micophoneClose} 
									alt={`Microphone ${micState}`} 
								/>
								<p>{micState === 'on' ? '麦克风开启' : '麦克风关闭'}</p>
							</div>

							{/* Leave meeting button */}
							<div 
								className="control-button leave-meeting"
								onClick={() => {
									Modal.confirm({
										title: '确认离开会议?',
										content: '您确定要离开会议吗？',
										okText: '确认',
										cancelText: '取消',
										onOk: () => {
											const roomId = new URLSearchParams(window.location.search).get('roomId');
											requestApi.updateRecord(roomId, {
												status: '已完成'
											}).then(() => {
												roomClient.close();
												micState = 'unsupported';
												this.setState({ meetingEnded: true });
												window.location.href = '/end.html';
											});
										}
									});
								}}
							>
								<img 
									src={leaveMeeting} 
									alt="Leave meeting" 
								/>
								<p>结束聊天</p>
							</div>

							{/* Speaker button */}
							<div 
								className="control-button"
								onClick={() => {
									this.setState(
										prevState => ({ speakerHighVolume: !prevState.speakerHighVolume }),
										() => {
											const volume = this.state.speakerHighVolume ? 1 : 0.2;
											if (this.peerViewRef.current) {
												this.peerViewRef.current.setAudioVolume(volume);
											} else {
												console.warn('PeerView ref not found');
											}
										}
									);
								}}
							>
								<img 
									src={this.state.speakerHighVolume ? cameraOpen : cameraClose}
									alt={`Speaker ${this.state.speakerHighVolume ? 'high volume' : 'normal volume'}`} 
								/>
								<p>{this.state.speakerHighVolume ? '扬声器开启' : '扬声器关闭'}</p>
							</div>
						</div>

						<ReactTooltip
							type="light"
							effect="solid"
							delayShow={100}
							delayHide={100}
							delayUpdate={50}
						/>
					</>
				)}

				{this.state.meetingEnded && (
					<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', position: 'absolute', top: '0', right: '0', bottom: '0', left: '0', fontSize: '16px', fontWeight: 'bold', textAlign: 'center', color: 'black' }}>
						会议已结束
					</div>
				)}
			</div>
		);
	}

	componentDidMount() {
		this._mounted = true;

		setTimeout(() => {
			if (!this._mounted || this.props.me.displayNameSet) return;

			ReactTooltip.show(this._rootNode);
		}, 4000);
	}

	componentWillUnmount() {
		this._mounted = false;
	}

	componentDidUpdate(prevProps) {
		if (!prevProps.me.displayNameSet && this.props.me.displayNameSet)
			ReactTooltip.hide(this._rootNode);
	}
}

Me.propTypes = {
	roomClient: PropTypes.any.isRequired,
	connected: PropTypes.bool.isRequired,
	me: appPropTypes.Me.isRequired,
	audioProducer: appPropTypes.Producer,
	onSetStatsPeerId: PropTypes.func.isRequired,
};

const mapStateToProps = state => {
	const producersArray = Object.values(state.producers);
	const audioProducer = producersArray.find(
		producer => producer.track.kind === 'audio'
	);

	return {
		connected: state.room.state === 'connected',
		me: state.me,
		audioProducer: audioProducer,
	};
};

const mapDispatchToProps = dispatch => {
	return {
		onSetStatsPeerId: peerId =>
			dispatch(stateActions.setRoomStatsPeerId(peerId)),
	};
};

const MeContainer = withRoomContext(
	connect(mapStateToProps, mapDispatchToProps)(Me)
);

export default MeContainer;
